package io.jplus.admin.controller;

import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import io.jboot.components.rpc.annotation.RPCInject;
import io.jboot.utils.StrUtil;
import io.jboot.web.controller.annotation.RequestMapping;
import io.jplus.JplusConsts;
import io.jplus.admin.model.Config;
import io.jplus.admin.service.ConfigService;
import io.jplus.core.web.base.BaseController;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import java.util.List;

@RequestMapping(value = "/admin/config", viewPath = JplusConsts.BASE_VIEW_PATH + "admin")
public class ConfigController extends BaseController {

    @RPCInject
    ConfigService configService;

    public void index() {
        render("config.html");
    }

    @RequiresPermissions("sys:config:list")
    public void list() {
        Page<Config> page = configService.queryPage(getQuery());
        renderJsonPage(page);
    }

    @RequiresPermissions("sys:config:info")
    public void info() {
        String configId = getPara();
        Config config = configService.findById(configId);
        renderJson(Ret.ok("config", config));
    }

    @Before(POST.class)
    @RequiresPermissions("sys:config:save")
    public void save() {
        Config config = jsonToModel(Config.class);
        String id = (String) configService.save(config);
        if (StrUtil.isNotBlank(id)) {
            renderJsonForSuccess();
        } else {
            renderJsonForFail("保存失败！");
        }
    }

    @Before(POST.class)
    @RequiresPermissions("sys:config:update")
    public void update() {
        Config config = jsonToModel(Config.class);
        boolean tag = configService.update(config);
        if (tag) {
            renderJsonForSuccess();
        } else {
            renderJsonForFail("更新失败！");
        }
    }

    @RequiresPermissions("sys:config:delete")
    public void delete() {
        List<Object> ids = jsonToList();
        if (ids == null) {
            renderJsonForFail("id不能为空！");
            return;
        }
        boolean tag = configService.deleteById(ids.toArray());
        if (tag) {
            renderJsonForSuccess();
        } else {
            renderJsonForFail("删除失败！");
        }
    }
}
